/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.h2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class H2Util {

    private static final Logger logger = Logger.getLogger(H2Util.class.getName());
    private static final String connectionStr = "jdbc:h2:file:data/test";
    private static final String driverClassName = "org.h2.Driver";
    private static Connection connection;
    private static Statement statement;

    static {
        try {
            // load the JDBC driver using the current class loader
            Class.forName(driverClassName);
        }
        catch (ClassNotFoundException ex) {
            logger.log(Level.SEVERE, "无法找到MySQL-JDBC驱动", ex);
        }

        try {
            connection = DriverManager.getConnection(connectionStr);

        }
        catch (SQLException ex) {
            logger.log(Level.SEVERE, "无法创建数据库连接对象", ex);
        }
        try {
            statement = connection.createStatement();
            statement.setQueryTimeout(30);  // set timeout to 30 sec.
        }
        catch (SQLException ex) {
            logger.log(Level.SEVERE, "无法创建数据库连接对象", ex);
        }


    }

    public static void main(String[] args) throws Exception {
        Connection conn = connection;
        PreparedStatement stmt = conn.prepareStatement("CREATE TABLE cc (GUID varchar(40) PRIMARY KEY,Data int,AddTime datetime)");
        stmt.execute();
        Random rand = new Random();

        long start = System.currentTimeMillis();
        stmt = conn.prepareStatement("INSERT INTO cc VALUES (RANDOM_UUID(), ?, NOW())");
        for (int i = 0; i < 100000; ++i) {
            stmt.setInt(1, rand.nextInt());
            stmt.execute();
        }
        long duration = System.currentTimeMillis() - start;
        conn.close();

        System.out.println("Finished in " + duration + " ms");
    }
}
